package enumandlambda;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2022-12-11-21:21
 */
public class CountDownLatchDemo1 {
    public static void main(String[] args) throws InterruptedException {
        //创建计数器
        CountDownLatch countDownLatch = new CountDownLatch(5);
        //线程池
        ExecutorService service = Executors.newFixedThreadPool(5);
        //创建新线程执行任务
        for (int i = 1; i < 6; i++) {
            service.submit(() -> {

                Thread currThread = Thread.currentThread();
                System.out.println(currThread.getName() +
                        ": 开始起跑");
                int runTime = (1 + new Random().nextInt(5));
                try {
                    TimeUnit.SECONDS.sleep(runTime);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
                System.out.println(currThread.getName() +
                        ": 到达终点，用时：" + runTime);
                countDownLatch.countDown();//计数器-1
            });
        }

        //阻塞等待，直到线程执行完
        countDownLatch.await();
        System.out.println("比赛结果宣布");
    }
}
